package com.ruoyi.web.controller.api;

import com.ruoyi.common.annotation.Anonymous;
import com.ruoyi.web.controller.service.EnterpriseInfoServiceImpl;
import com.ruoyi.web.controller.service.SseServer;
import org.apache.commons.lang3.RandomUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.annotation.Resource;
import java.io.IOException;

@Anonymous
@RestController
@RequestMapping("/sse")
public class SseDemoController {

    @Resource
    private EnterpriseInfoServiceImpl enterpriseInfoService;

    /**
     * 用户SSE连接
     * 它返回一个SseEmitter实例，这时候连接就已经创建了.
     */
    @GetMapping("/connect")
    public SseEmitter connect() {
        String userId = "userId-" + RandomUtils.nextInt(1, 10);
        SseEmitter connect = SseServer.createConnect(userId);
        try {
            connect.send(enterpriseInfoService.orderListLast());
        } catch (IOException e) {
            return null;
        }
        return connect;
    }

}
